/*
    项目名称: Reactor服务模型-测试客户端
    作者: 中国好青年(码农论坛)
    时间: 2024/9/4
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>

#define ERROR -1
#define OK    0

#define DEBUG

#ifdef DEBUG
#define IP "192.168.174.140"
#define PORT 5005
#endif
/* 
    函数名: int main(int argc, char* argv[])
    返回值: int, 程序执行完返回值,正常返回0,一般不返回,执行错误返回-1
    参  数: int argc,传入参数个数; char* argv[],参数值
    函数作用: 主函数入口  
*/
int main(int argc, char* argv[])
{
#ifndef DEBUG
    if(argc != 3)
    {
        printf("usage: ./client.exe ip port\n");
        printf("example: ./client.exe 192.168.174.140 5005\n");
        return ERROR;
    }
#endif
    //创建监听socket
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sockfd < 0)
    {
        printf("socket error()\n");
        return ERROR;
    }

    struct sockaddr_in servaddr;
    servaddr.sin_family = AF_INET;

#ifdef DEBUG
    servaddr.sin_addr.s_addr = inet_addr(IP);
    servaddr.sin_port = htons(PORT);
#else
    servaddr.sin_addr.s_addr = inet_addr(argv[1]);
    servaddr.sin_port = htons(atoi(argv[2]));
#endif

    if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0){
        printf("connect error \n");
        return ERROR;
    }
    printf("connect ok\n");
    char buff[1024];
    int n  = 2;
    //sleep(100);
    for(int i = 0; i < n; i++){
        //printf("%d  \n",i);
        bzero(buff, sizeof(buff));
        sprintf(buff,"第 %d 个数据",i);
        char tmpbuf[1024];
        bzero(tmpbuf, sizeof(tmpbuf));
        int len = strlen(buff);
        memcpy(tmpbuf, &len, 4);
        memcpy(tmpbuf+4,buff,len);

        if(send(sockfd, tmpbuf, len + 4, 0) < 0 )
        {
            printf("send error \n");
            return ERROR;
        }

    }                  
    for(int i = 0; i < n; i++)
    {   
        int len;
        ssize_t nread = read(sockfd, &len, 4);
         nread = read(sockfd, buff, len);
        if(nread > 0)
        {   
            printf("read:%s\n", buff);
        }else{
            printf("read error \n");
            return ERROR;
        }
        memset(buff, 0 , sizeof(buff));
    }                   
    printf("end\n");
    return 0;
}
